/**
 * 
 */
package fhq.hcmute.modernshopping.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import fhq.hcmute.modernshopping.ProjectUtil;
import fhq.hcmute.modernshopping.R;

/**
 * @author: Hien Nguyen Le
 * @emai: hien.nguyenle.it@gmail.com
 * 
 */
public class ListProductAdapter extends ArrayAdapter<Product> {

	private Context context;
	private List<Product> listProduct;

	public ListProductAdapter(Context context, List<Product> listProduct) {
		super(context, R.layout.lv_item_list_product, listProduct);
		this.context = context;
		this.listProduct = listProduct;
	}

	private static class ViewHolder {
		protected TextView txtProductName;
		protected TextView txtPrice;
	}

	@Override
	public int getCount() {
		return listProduct.size();
	}

	@Override
	public Product getItem(int position) {
		return listProduct.get(position);
	}

	public double getTotalCost() {
		double temp = 0;
		for (Product product : listProduct) {
			temp += product.getPrice() * product.getQuantity();
		}
		return temp;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = LayoutInflater.from(context);
			rowView = inflater.inflate(R.layout.lv_item_list_product, null);
			ViewHolder viewHolder = new ViewHolder();
			viewHolder.txtProductName = (TextView) rowView
					.findViewById(R.id.txt_product_name);
			viewHolder.txtPrice = (TextView) rowView
					.findViewById(R.id.txt_price);
			rowView.setTag(viewHolder);
		}
		ViewHolder holder = (ViewHolder) rowView.getTag();

		if (listProduct.size() > 0) {
			Product product = listProduct.get(position);

			String price = "%s %s x %d=%s %s";
			price = String.format(
					price,
					ProjectUtil.formatCurrency(product.getPrice()),
					context.getString(R.string.curency),
					product.getQuantity(),
					ProjectUtil.formatCurrency(product.getPrice()
							* product.getQuantity()),
					context.getString(R.string.curency));
			holder.txtPrice.setText(price);
			holder.txtProductName.setText(product.getName());
		}
		return rowView;
	}

	public void addProduct(Product product) {
		for (Product p : listProduct) {
			if (p.getCode() == product.getCode()) {
				int q = p.getQuantity() + product.getQuantity();
				p.setQuantity(q);
				notifyDataSetChanged();
				return;
			}
		}
		this.listProduct.add(product);
		notifyDataSetChanged();
	}

	public void update(Product product) {
		for (Product p : listProduct) {
			if (p.getCode() == product.getCode()) {
				p.setQuantity(product.getQuantity());
				notifyDataSetChanged();
				return;
			}
		}
	}

	public void refresh() {
		notifyDataSetChanged();
	}
}
